package cn.xingchen.web;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IDCardValidator {

    public static boolean validateIDCard(String idCard) {
        // 首先校验身份证号的长度是否合法
        if (idCard.length() != 18) {
            return false;
        }

        // 对前17位进行合法性校验
        for (int i = 0; i < 17; i++) {
            if (!Character.isDigit(idCard.charAt(i))) {
                return false;
            }
        }

        // 计算校验码
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            int ai = Integer.parseInt(String.valueOf(idCard.charAt(i)));
            int wi = (int) Math.pow(2, 17 - i) % 11;
            sum += ai * wi;
        }

        // 对校验码进行校验
        int checkCode = sum % 11;
        int lastCode = Integer.parseInt(String.valueOf(idCard.charAt(17)));
        if (checkCode == lastCode) {
            return true;
        } else {
            return false;
        }
    }











    //判断是否为有效身份证号
    public static boolean check(String str) {
        String patt="";

        if(str.length()==15)
            patt="^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$";
        else if(str.length()==18)
            patt="^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$";
        else
            return false;

        Pattern r = Pattern.compile(patt);
        Matcher matcher = r.matcher(str);
        return matcher.find();
    }




    public static void main(String[] args) {
//        String idCard = "330103199110251022";
//        boolean isValid = validateIDCard(idCard);
//        System.out.println("身份证号校验结果：" + isValid);

        System.out.println("350112198910081945 是否有效？"+check("350112198910081945"));
        System.out.println("54090119760311922X 是否有效？"+check("54090119760311922X"));
        System.out.println("050112198910081945 是否有效？"+check("050112198910081945"));
        System.out.println("130503670401001 是否有效？"+check("130503670401001"));
        System.out.println("-30503670401001 是否有效？"+check("-30503670401001"));
        System.out.println("330103199110251022 是否有效？"+check("330103199110251022"));

        System.out.println(IdCardCheckUtils.idCardNumberCheck("350112198910081945"));
        System.out.println(IdCardCheckUtils.idCardNumberCheck("54090119760311922X"));
        System.out.println(IdCardCheckUtils.idCardNumberCheck("050112198910081945"));
        System.out.println(IdCardCheckUtils.idCardNumberCheck("130503670401001"));
        System.out.println(IdCardCheckUtils.idCardNumberCheck("-30503670401001"));
        System.out.println(IdCardCheckUtils.idCardNumberCheck("330103199110251022"));



    }
}